import { useEffect } from 'react'
import { Routes, Route, Navigate, useNavigate, NavigateProps } from 'react-router-dom'

import { ConfigProvider, message } from 'antd'
import zhCN from 'antd/es/locale/zh_CN'

import { useDispatch, useSelector } from 'react-redux'
import { RootState } from './store'
import { set as setUserInfo } from './store/userInfo'

import Login from './pages/Login'
import Auth from './pages/auth/Index'
import Loading from './components/Loading'

import scss from './assets/scss/variable.module.scss'

import getEnv from './utils/env'
import { setMessage } from './utils/message'

import 'antd/dist/reset.css'
import './app.scss'
import NotFound from './NotFound'
import getRoutes from './router'

import { getUserInfo } from './api/user'

const name = getEnv('name')

function NavigateComponent({ to }: NavigateProps) {
  document.title = name
  return <Navigate to={to} />
}

function RouteComponent({ Component, meta }: RC) {
  document.title = meta.title ? meta.title + '_' + name : name
  return <Component />
}

function LoadingAuth() {
  const token = useSelector((state: RootState) => state.token)
  const dispatch = useDispatch()
  const nav = useNavigate()

  useEffect(() => {
    if (!token) return
    getUserInfo()
      .then((res) => {
        setTimeout(() => {
          dispatch(setUserInfo(res.data))
        }, 500)
      })
      .catch(() => {
        nav('/login')
      })
  }, [])

  return token ? <Loading /> : NavigateComponent({ to: '/login' })
}

function App() {
  const [messageApi, contextHolder] = message.useMessage()
  const userInfo = useSelector((state: RootState) => state.userInfo)
  const routes = getRoutes(userInfo?.role)

  setMessage(messageApi)

  return (
    <ConfigProvider
      locale={zhCN}
      theme={{
        components: {
          Table: {
            cellPaddingBlock: 12
          }
        },
        token: {
          colorPrimary: scss.theme,
          colorLink: scss.theme
        }
      }}
    >
      {contextHolder}
      <Routes>
        <Route path="/login" element={<RouteComponent Component={Login} meta={{ title: '登录' }} />} />
        {!routes.length ? (
          <Route path="/*" element={<LoadingAuth />} />
        ) : (
          <Route path="/" element={<RouteComponent Component={Auth} meta={{}} />}>
            <Route path="/" element={<NavigateComponent to={routes[0].path} />}></Route>
            {routes.map(({ path, Component, meta }) => {
              return <Route key={path} path={path} element={<RouteComponent Component={Component} meta={meta} />} />
            })}
          </Route>
        )}
        <Route path="*" element={<NotFound />} />
      </Routes>
    </ConfigProvider>
  )
}

export default App
